/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.example.file;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;

/**
 * Server that accept the path of a file an echo back its content.
 *
 * 文件服务器,作为 FTP的文件服务器
 * 接收一个文件路径 , 并将文件路径返回
 */
public final class FileServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    // Use the same default port with the telnet example so that we can use the telnet client example to access it.
    // 用telnet一样的默认端口 , 那么就可以使用Telnet来处理
    static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8992" : "8023"));

    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        // Configure the server.
        // TODO: 一直有个质疑 , BOSS 和WORKER 有什么用?
        // 服务端 boss eventLoop
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 服务端 worker eventLoop
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //服务端启动类
            ServerBootstrap b = new ServerBootstrap();
            //配置服务端EVENTLOOP
            b.group(bossGroup, workerGroup)
            //配置Nio Channel
             .channel(NioServerSocketChannel.class)
            // 等待队列,服务端一次只能处理一个请求 , 当有多个请求进入进,进入队列
            // 对应TCP网络编程中的listen方法
             .option(ChannelOption.SO_BACKLOG, 100)
            // 配置 日志服务
             .handler(new LoggingHandler(LogLevel.DEBUG))
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     // 配置 pipeline
                     ChannelPipeline p = ch.pipeline();
                     if (sslCtx != null) {
                         p.addLast(sslCtx.newHandler(ch.alloc()));
                     }
                     p.addLast(
                             new LoggingHandler(LogLevel.DEBUG),
                             // Encoder 输出 , 内容转为String 输出
                             new StringEncoder(CharsetUtil.UTF_8),
                             // Decoder 输入 , 将输入流解析, 去掉一帧中 , 的所有行尾符
                             new LineBasedFrameDecoder(8192),
                             // Decoder 输入,将输入流转码
                             new StringDecoder(CharsetUtil.UTF_8),
                             // TODO : what's this
                             new ChunkedWriteHandler(),
                             // 业务处理器
                             new FileServerHandler());
                 }
             });

            // Start the server.
            ChannelFuture f = b.bind(PORT).sync();

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
